import React, { useEffect, useState, useRef, useCallback } from "react";
import ReactMarkdown from "react-markdown";
import { Card, Spin, Progress, Button } from "antd";
import { UpOutlined, DownOutlined, LoadingOutlined } from "@ant-design/icons";
import FundamentalAgentAPI from "../api/strategies";

type Phase = "thinking" | "output" | "error";

interface NodeEvent {
  node: string;
  state: string;
  data: {
    phase: Phase;
    content: string;
    annotations?: any;
    model?: string;
    id?: string;
    index?: number;
  };
}

type NodeState = {
  thinking: string;
  output: string;
  phase: Phase | null;
  state: "idle" | "in_progress" | "done" | "error";
};

const NODE_ORDER = ["fundamental_A", "fundamental_B", "emotional_A", "conclusion"];

/** 每个 card 是否折叠 */
type FoldState = {
  [key: string]: boolean;
};

/** 每个节点的思考折叠 */
type ThinkingFoldState = {
  [key: string]: boolean;
};

export default function FundamentalChat({ stockName, stockCode, reportDate }: any) {
  const [nodes, setNodes] = useState<Record<string, NodeState>>(() =>
    NODE_ORDER.reduce((acc, n) => {
      acc[n] = { thinking: "", output: "", phase: null, state: "idle" };
      return acc;
    }, {} as Record<string, NodeState>)
  );

  const [isStreaming, setIsStreaming] = useState(false);

  /** 面板折叠 */
  const [collapsePanel, setCollapsePanel] = useState<FoldState>(() =>
    NODE_ORDER.reduce((acc, n) => {
      acc[n] = false;
      return acc;
    }, {} as FoldState)
  );

  /** 思考区域折叠 */
  const [collapseThinking, setCollapseThinking] = useState<ThinkingFoldState>(() =>
    NODE_ORDER.reduce((acc, n) => {
      acc[n] = true; // 默认折叠思考
      return acc;
    }, {} as ThinkingFoldState)
  );

  const bottomRef = useRef<HTMLDivElement | null>(null);
  const eventSourceRef = useRef<EventSource | null>(null);

  // 解析 SSE
  const parseStreamData = useCallback((jsonStr: string) => {
    try {
      const event: NodeEvent = JSON.parse(jsonStr);

      const nodeKey = event.node;
      const phase = event.data?.phase;
      const content = event.data?.content ?? "";
      const state =
        event.state === "done"
          ? "done"
          : event.state === "error"
          ? "error"
          : "in_progress";

      setNodes((prev) => {
        const prevNode = prev[nodeKey];
        if (!prevNode) return prev;

        return {
          ...prev,
          [nodeKey]: {
            thinking: phase === "thinking" ? prevNode.thinking + content : prevNode.thinking,
            output: phase === "output" ? prevNode.output + content : prevNode.output,
            phase,
            state,
          },
        };
      });
    } catch {
      console.warn("SSE JSON 解析失败: ", jsonStr);
    }
  }, []);

  // 自动滚动
  useEffect(() => {
    bottomRef.current?.scrollIntoView({ behavior: "smooth" });
  }, [nodes]);

  // 启动 SSE
  useEffect(() => {
    if (!stockName || !stockCode) return;

    // 重置状态
    setNodes(
      NODE_ORDER.reduce((acc, n) => {
        acc[n] = { thinking: "", output: "", phase: null, state: "idle" };
        return acc;
      }, {} as Record<string, NodeState>)
    );

    setIsStreaming(true);

    const userInput = `请分析股票 ${stockName} 的基本面`;

    const eventSource = FundamentalAgentAPI.streamAnalysis(
      userInput,
      stockCode,
      reportDate,
      (data) => parseStreamData(data)
    );

    eventSourceRef.current = eventSource;

    eventSource.onopen = () => {
      console.log("SSE 连接成功");
    };

    eventSource.onerror = (e) => {
      if (eventSource.readyState === EventSource.CLOSED) {
        console.log("SSE 正常关闭");
        return;
      }
      console.error("❌ SSE 错误:", e);
      setIsStreaming(false);
      eventSource.close();
    };

    eventSource.addEventListener("end", () => {
      console.log("流结束");
      eventSource.close();
      setIsStreaming(false);
    });

    return () => {
      try {
        eventSource.close();
      } catch {}
      eventSourceRef.current = null;
      setIsStreaming(false);
    };
  }, [stockName, stockCode, reportDate, parseStreamData]);

  /** 面板折叠按钮 */
  const togglePanel = (node: string) => {
    setCollapsePanel((prev) => ({
      ...prev,
      [node]: !prev[node],
    }));
  };

  /** 思考折叠按钮 */
  const toggleThinking = (node: string) => {
    setCollapseThinking((prev) => ({
      ...prev,
      [node]: !prev[node],
    }));
  };

  // 角色名称
  const renderNodeTitle = (node: string) => {
    switch (node) {
      case "fundamental_A":
        return "基本面研究员1(豆包)";
      case "fundamental_B":
        return "基本面研究员2(KIMI)";
      case "emotional_A":
        return "情绪面研究员1(KIMI)";
      case "conclusion":
        return "决策输出";
      default:
        return node;
    }
  };

  return (
    <div className="space-y-4 p-4 overflow-y-auto max-h-[100vh]">
      {NODE_ORDER.map((node) => {
        const item = nodes[node];
        const isInProgress = item.state === "in_progress" && isStreaming;
        const isDone = item.state === "done";
        const collapsed = collapsePanel[node];

        return (
          <Card
            key={node}
            title={
              <div className="flex items-center justify-between">
                <div>{renderNodeTitle(node)}</div>

                <div className="flex items-center gap-3">
                  {isInProgress && (
                    <div className="flex items-center text-gray-500">
                      <LoadingOutlined className="mr-1" /> 分析中...
                    </div>
                  )}
                  {isDone && <div className="text-green-600">✅ 已完成</div>}

                  {/* 控制整个面板折叠 */}
                  <Button
                    type="text"
                    size="small"
                    icon={collapsed ? <DownOutlined /> : <UpOutlined />}
                    onClick={() => togglePanel(node)}
                  />
                </div>
              </div>
            }
            className={`rounded-2xl shadow-sm border ${
              isDone && node === "conclusion"
                ? "border-green-300 bg-green-50"
                : "border-gray-100"
            }`}
          >
            {!collapsed && (
              <div className="whitespace-pre-wrap text-gray-800 leading-relaxed min-h-[60px]">
                {/* 思考过程 */}
                <div className="mt-2">
                  <div className="flex items-center justify-between">
                    <div className="text-sm text-gray-500">🧠 模型思考</div>

                    <Button
                      type="text"
                      size="small"
                      onClick={() => toggleThinking(node)}
                    >
                      {collapseThinking[node] ? "显示思考" : "收起思考"}
                    </Button>
                  </div>

                  {!collapseThinking[node] ? (
                    <div className="mt-2 text-gray-500 whitespace-pre-wrap">
                      {item.thinking || "(思考暂无内容)"}
                    </div>
                  ) : (
                    <div className="mt-2 text-gray-400 italic">
                      {item.thinking
                        ? item.thinking.split("\n")[0].slice(0, 120) +
                          (item.thinking.length > 120 ? "…" : "")
                        : "(思考已折叠)"}
                    </div>
                  )}

                  {/* 思考与输出之间加间距 */}
                  <div className="my-4 border-t pt-3"></div>

                  {/* === 正式输出（Markdown） === */}
                  <div>
                    <div className="text-sm font-medium text-gray-700 mb-1">正式输出</div>
                    <div className="text-gray-800">
                      <ReactMarkdown>
                        {item.output ||
                          (isInProgress ? "(等待正式输出…)" : "暂无正式输出")}
                      </ReactMarkdown>
                    </div>
                  </div>
                </div>
              </div>
            )}

            {isInProgress && (
              <div className="mt-3 flex items-center text-gray-500">
                <LoadingOutlined className="mr-2" /> 流式接收中…
                <Progress percent={30} size="small" showInfo={false} className="flex-1 ml-4" />
              </div>
            )}
          </Card>
        );
      })}

      <div ref={bottomRef} />

      {isStreaming ? (
        <div className="text-gray-500 flex items-center mt-4">
          <Spin size="small" className="mr-2" /> 正在研究中…
        </div>
      ) : (
        <div className="text-green-600 font-semibold mt-4">
          解析完成（或部分完成）
        </div>
      )}
    </div>
  );
}
